package com.kidback.bbloc259.wxapi;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.kidback.bbloc259.app.KidGlobal;
import com.kidback.bbloc259.network.base.ApiHelper;
import com.kidback.bbloc259.util.CollectionUtils;
import com.kidback.bbloc259.util.LogUtils;
import com.kidback.bbloc259.util.StringUtils;
import com.kidback.bbloc259.util.TipUtils;
import com.kidback.bbloc259.util.ToastUtils;
import com.mylhyl.circledialog.BaseCircleDialog;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by meikai on 2020/07/03.
 */
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private static final String TAG = "WXEntryActivity";

    public WXEntryActivity activity;
    public List<Disposable> disposableList = new ArrayList<>();
    private BaseCircleDialog loadingTipDialog;

    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity = this;
        super.onCreate(savedInstanceState);
        setContentView(new View(this));


        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, KidGlobal.WX_APP_ID, true);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void finish() {
        super.finish();
        Log.e("mk", "finish");
        overridePendingTransition(0, 0);
    }

    @Override
    public void onResp(BaseResp resp) { //在这个方法中处理微信传回的数据
        //形参resp 有下面两个个属性比较重要
        //1.resp.errCode
        //2.resp.transaction则是在分享数据的时候手动指定的字符创,用来分辨是那次分享(参照4.中req.transaction)
        switch (resp.errCode) { //根据需要的情况进行处理
            case BaseResp.ErrCode.ERR_OK:
                if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
                    //微信登录，正确返回，用户同意
                    String code = ((SendAuth.Resp) resp).code;
                    getAccessToken(code);
                } else if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
                    //微信分享
                    int type = ((SendMessageToWX.Resp) resp).getType();

                    if (StringUtils.equals(KidGlobal.SHARE_AWARD_TRANSACTION, ((SendMessageToWX.Resp) resp).transaction)) {
                        //分享领取奖励

                    }

                    finish();
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                //用户取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                //用户拒绝授权
                break;
            case BaseResp.ErrCode.ERR_SENT_FAILED:
                //发送失败
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                //不支持错误
                break;
            case BaseResp.ErrCode.ERR_COMM:
                //一般错误
                break;
            default:
                //其他不可名状的情况
                break;
        }
    }

    @Override
    public void onReq(BaseReq req) {
        //......这里是用来处理接收的请求,暂不做讨论
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (int i = 0; i < CollectionUtils.size(disposableList); i++) {
            Disposable disposable = CollectionUtils.get(disposableList, i);
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    }

    /**
     * 获取微信用户信息的访问令牌
     */
    private void getAccessToken(String code) {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

        okHttpClientBuilder.callTimeout(0, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.connectTimeout(10_000, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.writeTimeout(10_000, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.readTimeout(10_000, TimeUnit.MILLISECONDS);

        //官方请求日志
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(@NotNull String s) {
                Log.e("WXEntryActivity", s);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClientBuilder.addInterceptor(loggingInterceptor);
        OkHttpClient okHttpClient = okHttpClientBuilder.build();

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
        retrofitBuilder.baseUrl("https://api.weixin.qq.com/");
        retrofitBuilder.client(okHttpClient);
        retrofitBuilder.addConverterFactory(GsonConverterFactory.create());
        retrofitBuilder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        Retrofit retrofit = retrofitBuilder.build();

        WXService wxService = retrofit.create(WXService.class);

        String appid, secret;
        appid = KidGlobal.WX_APP_ID;
        secret = KidGlobal.WX_APP_AppSecret;

        Observable<JSONObject> observable = wxService.getAccessToken(appid, secret, code, "authorization_code");
        Observer<JSONObject> observer = new Observer<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposableList.add(d);
            }

            @Override
            public void onNext(JSONObject jsonObject) {
                String access_token = jsonObject.getString("access_token");
                String refresh_token = jsonObject.getString("refresh_token");
                String unionid = jsonObject.getString("unionid");
                String openid = jsonObject.getString("openid");
                String scope = jsonObject.getString("scope");
                Double expires_in_Double = jsonObject.getDouble("expires_in");
                double expires_in = expires_in_Double == null ? 0 : expires_in_Double.doubleValue();

                getWXUserInfo(access_token, openid);
            }

            @Override
            public void onError(Throwable e) {
                hideLoading();
                disposableList.add(TipUtils.showFail(activity, e.getMessage()));
            }

            @Override
            public void onComplete() {

            }
        };

        ApiHelper.request(observable, observer);
        showLoading("正在登录");

    }

    /**
     * 获取微信用户信息，如 openid、昵称、头像
     */
    private void getWXUserInfo(String access_token, String openid) {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

        okHttpClientBuilder.callTimeout(0, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.connectTimeout(10_000, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.writeTimeout(10_000, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.readTimeout(10_000, TimeUnit.MILLISECONDS);

        //官方请求日志
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(@NotNull String s) {
                Log.e("WXEntryActivity", s);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClientBuilder.addInterceptor(loggingInterceptor);
        OkHttpClient okHttpClient = okHttpClientBuilder.build();

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
        retrofitBuilder.baseUrl("https://api.weixin.qq.com/");
        retrofitBuilder.client(okHttpClient);
        retrofitBuilder.addConverterFactory(GsonConverterFactory.create());
        retrofitBuilder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        Retrofit retrofit = retrofitBuilder.build();

        WXService wxService = retrofit.create(WXService.class);

        Observable<WXUserInfo> observable = wxService.getWXUserInfo(access_token, openid, "");
        Observer<WXUserInfo> observer = new Observer<WXUserInfo>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposableList.add(d);
            }

            @Override
            public void onNext(WXUserInfo wxUserInfo) {

//                wxUserInfo.openid += "AA121341231";
//                wxUserInfo.nickname = "🤖🤖🤖👹🥶🤢";
//                wxUserInfo.headimgurl += "abc";

//                AppDataProvider.getInst().requestLogin(wxUserInfo);

                ToastUtils.show(wxUserInfo.nickname);

                LogUtils.e(wxUserInfo.toString());

                finish();
            }

            @Override
            public void onError(Throwable e) {
                disposableList.add(TipUtils.showFail(activity, e.getMessage()));
            }

            @Override
            public void onComplete() {
                hideLoading();
            }
        };

        ApiHelper.request(observable, observer);
    }

    public void showLoading(String msg) {
        hideLoading();

        loadingTipDialog = new CircleDialog.Builder()
                //添加标题，参考普通对话框
                .setProgressStyle(ProgressParams.STYLE_SPINNER)//STYLE_HORIZONTAL 或 STYLE_SPINNER
                .setProgressText(msg)// style = 水平样式时，text 支持 String.format() 例如：已经下载%s
                //添加按钮，参考普通对话框
                .show(getSupportFragmentManager());

    }

    public void hideLoading() {
        if (loadingTipDialog != null && !isDestroyed()) {
            loadingTipDialog.dismiss();
        }
    }


}